const bigFileUpload = require("../modules/upload/bigfileUpload");

async function uploadRoutes(fastify, options) {
  // 文件秒传校验
  fastify.get("/upload/check", async (request, reply) => {
    const { fileHash } = request.query;
    if (!fileHash) {
      return reply.code(400).send({ error: "缺少文件哈希" });
    }

    try {
      const result = await bigFileUpload.checkFile(fileHash);
      return result;
    } catch (error) {
      return reply.code(500).send({ error: error.message });
    }
  });

  // 获取分片上传状态
  fastify.get("/upload/chunk-status", async (request, reply) => {
    const { identifier } = request.query;
    if (!identifier) {
      return reply.code(400).send({ error: "缺少文件标识" });
    }

    try {
      const status = await bigFileUpload.getChunkStatus(identifier);
      return status;
    } catch (error) {
      return reply.code(500).send({ error: error.message });
    }
  });

  // 分片上传
  fastify.post("/upload/chunk", async (request, reply) => {
    try {
      const data = await request.file();
      if (!data) {
        return reply.code(400).send({ error: "未接收到文件数据" });
      }
      let chunkIndex = null;
      let identifier = null;
      let totalChunks = null;
      let fileName = null;
      let fileSize = null;
      let mimeType = null;
      if (data?.fields) {
        chunkIndex = data.fields.chunkIndex.value;
        identifier = data.fields.identifier.value;
        totalChunks = data.fields.totalChunks.value;
        fileName = data.fields.fileName.value;
        fileSize = data.fields.fileSize.value;
        mimeType = data.fields.mimeType.value;
      }
      const chunkIndexNum = parseInt(chunkIndex);
      const totalChunksNum = parseInt(totalChunks);
      const fileSizeNum = parseInt(fileSize);
      // 参数验证
      if (
        chunkIndexNum === undefined ||
        identifier === undefined ||
        totalChunksNum === undefined ||
        mimeType === undefined ||
        fileSizeNum === undefined ||
        fileName === undefined ||
        chunkIndexNum < 0 ||
        totalChunksNum <= 0 ||
        fileSizeNum < 0
      ) {
        return reply.code(400).send({ error: "缺少必要的参数或参数值不合法" });
      }
      // 验证文件类型和大小
      if (!bigFileUpload.validateFileType(mimeType)) {
        return reply.code(400).send({ error: "不支持的文件类型" });
      }
      if (!bigFileUpload.validateFileSize(fileSizeNum)) {
        return reply.code(400).send({ error: "文件大小超出限制" });
      }
      // 使用流式处理而不是加载整个文件到内存
      const result = await bigFileUpload.handleChunk(
        data.file,
        chunkIndexNum,
        identifier,
        totalChunksNum,
        {
          fileName: fileName,
          fileSize: fileSizeNum,
          mimeType: mimeType,
        }
      );
      return result;
    } catch (error) {
      return reply.code(500).send({ error: error.message });
    }
  });

  // 合并分片
  fastify.post("/upload/merge", async (request, reply) => {
    const { identifier, fileName, totalChunks } = request.body;
    if (!identifier || !fileName || !totalChunks) {
      return reply.code(400).send({ error: "参数不完整" });
    }

    try {
      // 启动异步合并任务并返回任务ID
      const result = await bigFileUpload.mergeChunks(
        identifier,
        fileName,
        totalChunks
      );
      return {
        ...result,
        message: "文件合并任务已启动，请通过WebSocket监听合并进度",
      };
    } catch (error) {
      return reply.code(500).send({ error: error.message });
    }
  });
}

module.exports = uploadRoutes;